<template>
    <div class="ai-character" ref="container">
      <!-- 3D模型容器 -->
      <div class="character-model" ref="modelContainer">
        <div class="placeholder-model" v-if="!modelLoaded">
          <div class="spinner"></div>
          <p>✨ 加载人物模型中... ✨</p>
        </div>
      </div>
      
      <!-- 控制区 -->
      <div class="character-controls">
        <button @click="speak" class="action-btn">双击对话</button>
        <button @click="toggleDance" class="action-btn">
          {{ isDancing ? '⏹️ 停止' : '💃 跳舞' }}
        </button>
        <!-- <button @click="showInfo" class="action-btn">ℹ️ 信息</button> -->
      </div>
     
    </div>
   
  </template>
 
  <script setup>
  import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
  import * as THREE from 'three'
  import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
  import { AnimationMixer } from 'three'

  
  
  
  // 响应式props
  const props = defineProps({
    modelScale: {
      type: Number,
      default: 0.8
    },
    initialCameraZ: {
      type: Number,
      default: 5
    },
    aspectRatio: {
      type: Number,
      default: 16/9
    }
  })
  
  // 状态管理
  const container = ref(null)
  const modelContainer = ref(null)
  const modelLoaded = ref(false)
  const isDancing = ref(false)
  const secretMessage = ref('')
  const encryptedResult = ref('')
  const containerSize = ref({ width: 0, height: 0 })
  
  // Three.js核心变量
  let scene, camera, renderer, model, mixer, clock, idleAction, danceAction, animationId
  let resizeObserver = null
  
  // 初始化3D场景
  function initThreeJS() {
    if (!modelContainer.value) return
  
    try {
      // 创建场景
      scene = new THREE.Scene()
      scene.background = new THREE.Color(0xf0f0f0)
      
      // 创建相机（基于容器尺寸）
      const { width, height } = containerSize.value
      camera = new THREE.PerspectiveCamera(
        45,
        width / height,
        0.1,
        100
      )
      camera.position.set(0, 0.5, props.initialCameraZ)
      
      // 创建渲染器
      renderer = new THREE.WebGLRenderer({ 
        antialias: true,
        alpha: true
      })
      renderer.setSize(width, height)
      renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // 限制高DPI设备的性能消耗
      modelContainer.value.appendChild(renderer.domElement)
      
      // 添加光源
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.6)
      scene.add(ambientLight)
      
      const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
      directionalLight.position.set(3, 5, 4)
      scene.add(directionalLight)
      
      // 加载模型
      const loader = new GLTFLoader()
      loader.load(
        'https://threejs.org/examples/models/gltf/RobotExpressive/RobotExpressive.glb',
        (gltf) => {
          model = gltf.scene
          
          // 基于容器尺寸动态调整模型大小
          const scaleFactor = calculateModelScale(width)
          model.scale.set(scaleFactor, scaleFactor, scaleFactor)
          model.position.y = -1
          
          scene.add(model)
          
          // 初始化动画系统
          clock = new THREE.Clock()
          mixer = new AnimationMixer(model)
          
          // 解析动画剪辑
          const animations = gltf.animations
          idleAction = mixer.clipAction(animations[0])
          idleAction.play()
          
          danceAction = mixer.clipAction(animations[3])
          danceAction.setLoop(THREE.LoopRepeat, Infinity)
          
          modelLoaded.value = true
          startAnimationLoop()
        },
        (progress) => {
          console.log(`模型加载中: ${Math.round(progress.loaded / progress.total * 100)}%`)
        },
        (error) => {
          console.error('模型加载失败:', error)
          modelLoaded.value = false
        }
      )
    } catch (error) {
      console.error('初始化失败:', error)
    }
  }
  
  // 计算模型缩放比例（基于容器宽度）
  function calculateModelScale(containerWidth) {
    // 基础缩放
    let scale = props.modelScale
    
    // 在小屏幕上自动缩小模型
    if (containerWidth < 400) {
      scale *= 0.7
    } else if (containerWidth < 600) {
      scale *= 0.85
    }
    
    return scale
  }
  
  // 动画循环
  function startAnimationLoop() {
    const animate = () => {
      animationId = requestAnimationFrame(animate)
      if (mixer && clock) {
        mixer.update(clock.getDelta())
      }
      if (renderer) {
        renderer.render(scene, camera)
      }
    }
    animate()
  }
  
  // 更新容器尺寸
  function updateContainerSize() {
    if (!container.value) return
    
    const rect = container.value.getBoundingClientRect()
    const width = rect.width
    const height = Math.round(width / props.aspectRatio) // 基于宽高比计算高度
    
    containerSize.value = { width, height }
    
    // 更新模型容器样式
    if (modelContainer.value) {
      modelContainer.value.style.width = `${width}px`
      modelContainer.value.style.height = `${height}px`
    }
    
    // 更新渲染器
    if (renderer && camera) {
      camera.aspect = width / height
      camera.updateProjectionMatrix()
      renderer.setSize(width, height)
      
      // 调整模型缩放
      if (model) {
        const scaleFactor = calculateModelScale(width)
        model.scale.set(scaleFactor, scaleFactor, scaleFactor)
      }
    }
  }
  
  // 切换跳舞状态
  function toggleDance() {
    if (!mixer || !idleAction || !danceAction) {
      alert('动画系统未准备好，请稍等模型加载完成')
      return
    }
    
    isDancing.value = !isDancing.value
    
    if (isDancing.value) {
      idleAction.fadeOut(0.5)
      danceAction.reset().fadeIn(0.5).play()
    } else {
      danceAction.fadeOut(0.5)
      idleAction.reset().fadeIn(0.5).play()
    }
  }
  
  // 其他交互函数
  function speak() {
  

  }
  
//   function showInfo() {
//     alert('姓名: Aurora\n年龄: 22岁\n性格: 活泼开朗\n特长: 跳舞、对话、加密')
//   }
  

  
  // 生命周期管理
  onMounted(() => {
    nextTick(() => {
      // 初始化尺寸
      updateContainerSize()
      
      // 初始化Three.js
      initThreeJS()
      
      // 设置resize观察器
      resizeObserver = new ResizeObserver(() => {
        updateContainerSize()
      })
      
      if (container.value) {
        resizeObserver.observe(container.value)
      }
      
      // 监听窗口大小变化
      window.addEventListener('resize', updateContainerSize)
    })
  })
  
  onUnmounted(() => {
    // 清理资源
    if (animationId) cancelAnimationFrame(animationId)
    if (mixer) mixer.stopAllAction()
    if (renderer) {
      renderer.dispose()
      renderer.forceContextLoss()
    }
    if (resizeObserver && container.value) {
      resizeObserver.unobserve(container.value)
    }
    window.removeEventListener('resize', updateContainerSize)
  })
  
  // 监听props变化
  watch(() => props.modelScale, () => {
    if (model && containerSize.value.width) {
      const scaleFactor = calculateModelScale(containerSize.value.width)
      model.scale.set(scaleFactor, scaleFactor, scaleFactor)
    }
  })
  </script>
  
  <style scoped>
  .ai-character {
    width: 200px;
    min-width: 150px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 20px;
    padding: 0px;
    /* box-shadow: 0 8px 32px rgba(0,0,0,0.1); */
    box-sizing: border-box;
  }
  
  .character-model {
    background-color: rgba(255,255,255,0.9);
    border-radius: 15px;
    margin-bottom: 7px;
    overflow: hidden;
    position: relative;
    /* 尺寸由JS动态设置 */
  }
  
  .placeholder-model {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #6a8caf;
    font-size: 18px;
  }
  
  .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(106, 140, 175, 0.3);
    border-radius: 50%;
    border-top-color: #6a8caf;
    animation: spin 1s linear infinite;
    margin-bottom: 15px;
  }
  
  @keyframes spin {
    to { transform: rotate(360deg); }
  }
  
  .character-controls {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
  }
  
  .action-btn {
  background-color: #6a8caf;
  color: white;
  border: none;
  /* 固定宽高 */
  width: 55px; /* 固定宽度 */
  height: 25px; /* 固定高度 */
  /* 内边距调整文字位置（避免文字贴边） */
  padding: 0 10px; 
  font-size: 10px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center; /* 文字居中 */
  gap: 5px;
  white-space: nowrap;
}
  
  .action-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
  }
  
  .security-feature input {
    flex: 1;
    padding: 5px 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    min-width: 120px;
  }
  /* 响应式调整 */
  @media (max-width: 480px) {
    .action-btn {
      padding: 8px 12px;
      font-size: 14px;
    }
    
    .security-feature {
      padding: 10px;
    }
    
    .encrypt-group {
      flex-direction: column;
    }
    
    .security-feature input, .encrypt-btn {
      width: 100%;
      margin-left: 0;
    }
  }
  </style>